package com.cnjson.sensor.db.utils;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @Auther: zhy
 * @Date: 2019/11/20
 * @Description: 日期转换工具
 */
public class DateUtils {

    /**
     * 将当前的日期转成16进制字符串
     *
     * @param date 时间
     * @return  String
     */
    public static String datetoHex(LocalDateTime date) {
        StringBuffer sb = new StringBuffer();

        // 年月日 时分秒
        sb.append(Integer.toHexString(date.getYear() % 1000));

        String monthHex = Integer.toHexString(date.getMonthValue());
        sb.append(monthHex.length() == 1 ? 0 + monthHex : monthHex);

        String dayHex = Integer.toHexString(date.getDayOfMonth());
        sb.append(dayHex.length() == 1 ? 0 + dayHex : dayHex);

        String hourHex = Integer.toHexString(date.getHour());
        sb.append(hourHex.length() == 1 ? 0 + hourHex : hourHex);

        String minuteHex = Integer.toHexString(date.getMinute());
        sb.append(minuteHex.length() == 1 ? 0 + minuteHex : minuteHex);

        String secondHex = Integer.toHexString(date.getSecond());
        sb.append(secondHex.length() == 1 ? 0 + secondHex : secondHex);

        return sb.toString();
    }


    /**
     * 将字节数组转成对应的日期时间
     *
     * @param dateBytes 日期的字节数组
     * @return
     */
    public static Date hexBytesToDate(byte[] dateBytes) {
        StringBuffer sb = new StringBuffer();
        int year = dateBytes[0];
        int month = dateBytes[1];
        int day = dateBytes[2];
        int hour = dateBytes[3];
        int minutes = dateBytes[4];
        int seconds = dateBytes[5];

        // 生成日期字符串
        sb.append("20" + year);
        sb.append(month > 9 ? month : 0 + "" + month);
        sb.append(day > 9 ? day : 0 + "" + day);
        sb.append(hour > 9 ? hour : 0 + "" + hour);
        sb.append( minutes > 9 ? minutes : 0 + "" + minutes);
        sb.append(seconds > 9 ? seconds : 0 + "" + seconds);
        String dateStr = sb.toString();

        // 转成date

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        LocalDateTime dateTime = LocalDateTime.parse(dateStr, dtf);
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
//        Date date = null;
//        try {
//            date = sdf.parse(dateStr);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
        return Date.from(dateTime.toInstant(ZoneOffset.of("+8")));
    }

    public static void main(String[] args) {
        String string = "";
        byte[] dateByte = new byte[]{0x13,0x11,0x17};
        int i = Integer.parseInt(Integer.toHexString(dateByte[0]), 16);
        int year = dateByte[0];
        System.out.println(i);
        System.out.println(year);
    }

}
